package com.dragon.modules.yuegou.web;


import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;

/**
 * 客户端信息
 * 
 * @author liuwu
 *
 */
public class ClientInfo {

	private static final String MAC_HEADER_NAME = "X-MAC";
	private static final String APPID_HEADER_NAME = "X-App-ID";
	private static final String VERSION_HEADER_NAME = "X-App-Version";
	private static final String UA_HEADER_NAME = "User-Agent";

	/**
	 * 获取当前客户端信息<br>
	 * 请注意，只能在HTTP请求线程使用，在后台线程中调用这个方法将会抛出异常
	 * <code>ClientInfo info = ClientInfo.current();</code>
	 * 
	 * @return 当前请求携带的客户端信息
	 */
	public static ClientInfo current() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
		return new ClientInfo(request.getHeader(MAC_HEADER_NAME), request.getHeader(APPID_HEADER_NAME),
				request.getHeader(VERSION_HEADER_NAME), request.getHeader(UA_HEADER_NAME),
				WebUtils.getRealClientIp(request));
	}

	/**
	 * 客户端MAC地址
	 */
	@Nullable
	private final String mac;

	/**
	 * 应用ID
	 */
	private final String appid;

	/**
	 * 客户端版本号
	 */
	private final String version;

	/**
	 * 客户端UA
	 */
	private final String userAgent;

	/**
	 * 客户端IP
	 */
	private final String ip;

	public ClientInfo(@Nullable String mac, String appid, String version, String userAgent, String ip) {
		super();
		Check.notEmpty(appid, "请提供应用ID");
		Check.notEmpty(version, "请提供应用版本");
		this.mac = mac;
		this.appid = appid;
		this.version = version;
		this.userAgent = userAgent;
		this.ip = ip;
	}

	public String getMac() {
		return mac;
	}

	public String getAppid() {
		return appid;
	}

	public String getVersion() {
		return version;
	}

	public String getUserAgent() {
		return userAgent;
	}

	public String getIp() {
		return ip;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("ClientInfo [");
		if (mac != null) {
			builder.append("mac=");
			builder.append(mac);
			builder.append(", ");
		}
		if (appid != null) {
			builder.append("appid=");
			builder.append(appid);
			builder.append(", ");
		}
		if (version != null) {
			builder.append("version=");
			builder.append(version);
			builder.append(", ");
		}
		if (userAgent != null) {
			builder.append("userAgent=");
			builder.append(userAgent);
			builder.append(", ");
		}
		if (ip != null) {
			builder.append("ip=");
			builder.append(ip);
		}
		builder.append("]");
		return builder.toString();
	}

}
